﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsvHelper;
using System.IO;

namespace Simple.Common.Core.Csv
{
    /// <summary>
    /// CsvHelper 插件简单应用
    /// </summary>
    public static class SimpleCsvHelper
    {
        /// <summary>
        /// 读取
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="fileName">文件路径</param>
        /// <param name="encoding">编码格式(默认UTF8)</param>
        /// <returns></returns>
        public static IEnumerable<TResult> Read<TResult>(string fileName, Encoding encoding=null) where TResult : class
        {
            if (encoding == null) encoding = Encoding.UTF8;
            using (TextReader txtReader = new StreamReader(fileName, encoding))
            {
                using (var reader = new CsvReader(txtReader))
                {
                    return reader.GetRecords<TResult>();
                }
            }
        }

        /// <summary>
        /// 写入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">文件路径</param>
        /// <param name="records">数据集合</param>
        /// <param name="encoding">编码格式(默认UTF8)</param>
        public static void Write<T>(string fileName, IList<T> records, Encoding encoding=null) where T : class
        {
            if (encoding == null) encoding = Encoding.UTF8;
            using (TextWriter txtWriter = new StreamWriter(fileName, false, encoding))
            {
                using (var writer = new CsvWriter(txtWriter))
                {
                    writer.WriteRecords(records);
                }
            }
        }


    }

}
